//
//  MLOAuthViewController.swift
//  SinaWeibo
//
//  Created by 李亮亮 on 16/4/9.
//  Copyright © 2016年 Big Fish. All rights reserved.
//

import UIKit
import SVProgressHUD


class MLOAuthViewController: UIViewController {

    // 自定义根视图为webView
    let webView = UIWebView()
    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        setupUI()
        
        loadWebView()
        
    }
    
    // 设置导航条
    func setupUI() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "关闭", imageName: nil, target: self, action: #selector(MLOAuthViewController.close))
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "测试账户", imageName: nil, target: self, action: #selector(MLOAuthViewController.fullAccount))
    }
    
    // 使用webView加载授权页面
    func loadWebView() {
        
        let urlString = authorize + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL: url!)
        webView.loadRequest(request)
        
    }
    
    // 关闭
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    // 自动填写测试账户密码
    func fullAccount() {
        
        webView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = '595884982@qq.com' , document.getElementById('passwd').value = 'lll0317' ")
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        // 取消HUD
        SVProgressHUD.dismiss()
    }
    
}


extension MLOAuthViewController: UIWebViewDelegate {
    
    // 开始加载页面
    func webViewDidStartLoad(webView: UIWebView) {
        // 开启指示器
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
      
        let webTitle = webView.stringByEvaluatingJavaScriptFromString("document.title")
        navigationItem.title = webTitle
        
        // 取消用户等待指示器
        SVProgressHUD.dismiss()
    }
    
    // 协议方法返回值为Bool, 如果返回true就可以正常工作, 如果返回false就不能够工作
    // 在授权成功的回调页中获取 授权code
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlString = request.URL?.absoluteString ?? ""
        // 满足字符串中包含了 code=
//        print(urlString)
        let flag = "code="
        if urlString.containsString(flag) {
            // 授权成功
            let range = urlString.rangeOfString(flag)!
            let code = urlString.substringFromIndex((range.endIndex))
            print(code)
            // 使用授权码code, 获取accessToken
//            loadAccessToken(code)
            MLUserAccountViewModel.sharedUserAccountViewModel.loadAccessToken(code, finished: { (isSuccess) in
                if !isSuccess {
                    // 表示登录失败
                    SVProgressHUD.showErrorWithStatus("登录失败")
                    return
                }
                
                // TODO: 跳转到欢迎页面
                // 单例对象的account有值吗?  单例对象的模型没有赋值
            
                // 跳转到欢迎页面(用户名 + 用户头像)
//                SVProgressHUD.showSuccessWithStatus("登录成功")
                self.dismissViewControllerAnimated(false, completion: { 
                    NSNotificationCenter.defaultCenter().postNotificationName(MLSwitchRootViewController, object: nil)
                })
            })
            // 不加载授权成功的回调页面
            return false
        }
        
        print(urlString)
        return true
    }
    
    
}


